'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { updateMenu } from '@/services/api';
import type { TBody, TMenuMenuType } from '@/types';
import type { IDifference, IMenu, IUpdateMenuBody } from '@/interfaces';
import diff from 'microdiff';
import useToast from '@/hooks/useToast';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';

export default function UpdateMenuInfo(
  this: any,
  {
    details,
  }: {
    details: IMenu;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    name: string;
    path: string;
    sort: number;
    menuType: TMenuMenuType;
  }>({
    name: '',
    path: '',
    sort: 0,
    menuType: 'LINK',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);

  const updateMenuMutation = useMutation(
    async (variables: TBody<IUpdateMenuBody>) => {
      await updateMenu(variables);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        name: details.name,
        path: details.path,
        sort: details.sort,
        menuType: details.menuType,
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          name: details.name,
          path: details.path,
          sort: details.sort,
          menuType: details.menuType,
        },
        form,
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'sort') {
      setForm({ ...form, sort: parseInt(value) });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateMenuMutation.mutateAsync({
        id: details.id,
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateMenuMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">名称</label>
            <input
              type="text"
              className="form-control"
              name="name"
              value={form.name}
              onChange={onChangeForm}
              aria-describedby="name"
              placeholder="请输入菜单名称"
            />
          </div>

          <div>
            <label className="form-label">路径</label>
            <input
              type="text"
              className="form-control"
              name="path"
              value={form.path}
              onChange={onChangeForm}
              aria-describedby="path"
              placeholder="请输入菜单路径"
            />
          </div>

          <div>
            <label className="form-label">排序</label>
            <input
              type="number"
              className="form-control"
              min={0}
              name="sort"
              value={form.sort}
              onChange={onChangeForm}
              aria-describedby="sort"
              placeholder="请输入菜单排序，最小值为 0"
            />
          </div>

          <div>
            <label className="form-label">类型</label>
            <select
              name="menuType"
              value={form.menuType}
              onChange={onChangeForm}
              className="form-select"
              aria-label="菜单类型"
              placeholder="请选择菜单类型"
            >
              <option>请选择菜单类型</option>
              <option value="LINK">链接</option>
              <option value="BUTTON">按钮</option>
            </select>
          </div>

          <button
            type="submit"
            disabled={updateMenuMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updateMenuMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
